package com.whfc.ms.api.quality.controller;

import com.whfc.common.base.BaseController;
import com.whfc.common.result.ListData;
import com.whfc.common.result.R;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.AssertUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.entity.SysUser;
import com.whfc.ms.api.quality.service.MsQualityCheckService;
import com.whfc.ms.config.AbstractBaseController;
import com.whfc.quality.dto.QualityCheckPartStatisticalDTO;
import com.whfc.quality.dto.QualityCheckScreenDTO;
import com.whfc.quality.dto.QualityCheckUnfinishedDTO;
import com.whfc.quality.dto.QualityLogDTO;
import com.whfc.quality.param.QualityCheckLogParam;
import com.whfc.quality.param.QualityCheckParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClasssName QualityCheckController
 * @Description 质量管理问题请求类
 * @Author hw
 * @Date 2020/8/3 11:07
 * @Version 1.0
 */
@RequiresPermissions(value = {"quality/record", "quality/check"}, logical = Logical.OR)
@RestController
@RequestMapping("/ms/api/quality/check")
public class QualityCheckController extends AbstractBaseController {

    @Autowired
    private MsQualityCheckService msQualityCheckService;


    @GetMapping("/list")
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @RequestParam("deptId") Integer deptId,
                       @RequestParam(value = "type", required = false) String type,
                       @RequestParam(value = "state", required = false) String state,
                       @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                       @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
                       @RequestParam(value = "urgency", required = false) Integer urgency,
                       @RequestParam(value = "overdue", required = false) Integer overdue,
                       @RequestParam(value = "partId", required = false) Integer partId,
                       @RequestParam(value = "pageNum", required = false) Integer pageNum,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        logger.info("质量问题上报列表,loginer:{},deptId:{},type:{},state:{},startTime:{},endTime:{},urgency:{},overdue:{},partId:{},pageNum:{},pageSize{}",
                user.getUsername(), deptId, type, state, startTime, endTime, urgency, overdue, partId, pageNum, pageSize);
        Integer[] types = null;
        Integer[] states = null;
        if (StringUtils.isNotEmpty(type)) {
            types = Arrays.stream(type.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
        }
        if (StringUtils.isNotEmpty(state)) {
            states = Arrays.stream(state.split(",")).map(Integer::valueOf).toArray(Integer[]::new);
        }
        return ResultUtil.success(msQualityCheckService.getCheckList(deptId, types, states, startTime, endTime, partId, urgency, overdue, user.getId(), pageNum, pageSize));
    }


    @GetMapping("/desc")
    public Result desc(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @RequestParam("checkId") Integer checkId) {
        logger.info("质量问题上报列表,loginer:{},checkId:{}",
                user.getUsername(), checkId);
        return ResultUtil.success(msQualityCheckService.desc(checkId));
    }

    @RequiresPermissions("quality/record/problemReport")
    @PostMapping("/add")
    public Result add(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @Validated @RequestBody QualityCheckParam checkParam) {
        logger.info("质量问题上报,loginer:{},checkParam:{}", user.getUsername(), checkParam.toString());
        AssertUtil.isTrue(checkParam.getRectifyDuration().before(new Date()),"整改期限不能设置在当前时间之前");
        msQualityCheckService.add(checkParam, user);
        return ResultUtil.success();
    }

    @RequiresPermissions(value = "quality/record/del")
    @PostMapping("/del/{checkId}")
    public Result del(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @PathVariable("checkId") Integer checkId) {
        logger.info("质量问题删除, loginer:{}, checkId:{}", user.getUsername(), checkId);
        msQualityCheckService.del(checkId);
        return ResultUtil.success();
    }

    @GetMapping("/user/list")
    public Result userList(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @RequestParam("deptId") Integer deptId) {
        logger.info("人员信息查询,loginer:{},deptId:{}", user.getUsername(), deptId);
        return ResultUtil.success(msQualityCheckService.sysUserList(deptId));
    }

    @PostMapping("/log")
    public Result addLog(@SessionAttribute(SessionAttr.MS_USER) SysUser user, @Validated @RequestBody QualityCheckLogParam qualityCheckLogParam) {
        logger.info("问题处理流程接口,loginer:{},deptId:{}", user.getUsername(), qualityCheckLogParam.toString());
        qualityCheckLogParam.setOpUserId(user.getId());
        qualityCheckLogParam.setOpUserName(user.getNickname());
        msQualityCheckService.addLog(qualityCheckLogParam);
        return ResultUtil.success();
    }

    @GetMapping(value = "/statistics", params = {"startTime", "endTime"})
    public Result statistics(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("deptId") Integer deptId,
                             @RequestParam(value = "userId", required = false) Integer userId,
                             @RequestParam("startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                             @RequestParam("endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        logger.info("统计分析查询,loginer:{},deptId:{},userId:{},startTime:{},endTime:{}", user.getUsername(), deptId, userId, startTime, endTime);
        return ResultUtil.success(msQualityCheckService.statistics(deptId, userId, startTime, endTime));
    }


    @GetMapping(value = "/statistics", params = {"dayTime"})
    public Result statisticsDay(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                @RequestParam("deptId") Integer deptId,
                                @RequestParam(value = "userId", required = false) Integer userId,
                                @RequestParam("dayTime") @DateTimeFormat(pattern = "yyyy-MM-dd") Date dayTime) {
        logger.info("统计分析查询,loginer:{},deptId:{},userId:{},dayTime:{}", user.getUsername(), deptId, userId, dayTime);
        return ResultUtil.success(msQualityCheckService.statisticsDay(deptId, userId, dayTime));
    }

    @GetMapping(value = "/statistics", params = {"monthTime"})
    public Result statisticsMonth(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                  @RequestParam("deptId") Integer deptId,
                                  @RequestParam(value = "userId", required = false) Integer userId,
                                  @RequestParam("monthTime") @DateTimeFormat(pattern = "yyyy-MM") Date monthTime) {
        logger.info("统计分析查询,loginer:{},deptId:{},,userId:{}monthTime:{}", user.getUsername(), deptId, userId, monthTime);
        return ResultUtil.success(msQualityCheckService.statisticsMonth(deptId, userId, monthTime));
    }

    @PostMapping("/uploadImg")
    public Result uploadImg(@SessionAttribute(SessionAttr.MS_USER) SysUser user, MultipartFile file) {
        logger.info("问题上报图片上传,loginer:{}", user.getUsername());
        String imgUrl = msQualityCheckService.uploadImg(file);
        if (StringUtils.isBlank(imgUrl)) {
            return ResultUtil.failure("图片上传失败");
        }
        return ResultUtil.success(imgUrl);
    }

    @GetMapping("/log")
    public Result qualityLog(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("deptId") Integer deptId,
                             @RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        logger.info("质量日志,loginer:{},deptId:{},date:{}", user.getUsername(), deptId, date);
        QualityLogDTO data = msQualityCheckService.qualityLog(deptId, date);
        return ResultUtil.success(data);
    }

    @GetMapping("/export")
    public Result export(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                         @RequestParam("deptId") Integer deptId,
                         @RequestParam("qualityIds") String qualityIds) {
        logger.info("质量问题上报导出,loginer:{},deptId:{},qualityIds:{}", user.getUsername(), deptId, qualityIds);
        msQualityCheckService.export(qualityIds, deptId);
        return ResultUtil.success();
    }

    @GetMapping("statistical")
    public Result qualityCheckScreenStatistical(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                                @RequestParam("deptId") Integer deptId,
                                                @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                                @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        logger.info("检查统计,loginer:{},deptId:{},startTime:{},endTime:{}", user.getUsername(), deptId, startTime, endTime);
        QualityCheckScreenDTO data = msQualityCheckService.qualityCheckScreenStatistical(deptId, startTime, endTime);
        return ResultUtil.success(data);
    }

    @GetMapping("type/analysis")
    public Result qualityCheckTypeAnalysis(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                           @RequestParam("deptId") Integer deptId,
                                           @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                           @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        logger.info("上报问题类别分析,loginer:{},deptId:{},startTime:{},endTime:{}", user.getUsername(), deptId, startTime, endTime);
        QualityCheckScreenDTO data = msQualityCheckService.qualityCheckTypeAnalysis(deptId, startTime, endTime);
        return ResultUtil.success(data);
    }

    @GetMapping("question/unfinished")
    public Result qualityCheckUnfinished(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                         @RequestParam("deptId") Integer deptId,
                                         @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                         @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        logger.info("未销问题分析,loginer:{},deptId:{},startTime:{},endTime:{}", user.getUsername(), deptId, startTime, endTime);
        QualityCheckUnfinishedDTO data = msQualityCheckService.qualityCheckUnfinished(deptId, startTime, endTime);
        return ResultUtil.success(data);
    }

    @GetMapping("/part/analysis")
    public Result qualityCheckPartAnalysis(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                           @RequestParam("deptId") Integer deptId,
                                           @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                           @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        logger.info("上报问题部位分析,loginer:{},deptId:{},startTime:{},endTime:{}", user.getUsername(), deptId, startTime, endTime);
        ListData<QualityCheckPartStatisticalDTO> data = msQualityCheckService.qualityCheckPartAnalysis(deptId, startTime, endTime);
        return ResultUtil.success(data);
    }


    /**
     * 2.0质量检查记录批量删除
     *
     * @param idList
     * @return
     */
    @RequiresPermissions(value = "quality/record/del")
    @PostMapping("/delete/batch")
    public R deleteBatch(@RequestBody List<Integer> idList) {
        logger.info("质量检查记录批量删除,userId:{},idList:{}", getLoginUser().getId(), idList);
        AssertUtil.isTrue(CollectionUtils.isEmpty(idList), "ID不能为空");
        msQualityCheckService.deleteBatch(idList);
        return R.success();
    }
}
